package com.lcj.bff.driver.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.map.MapUtil;
import com.lcj.bff.driver.controller.form.*;
import com.lcj.bff.driver.service.DriverLocationService;
import com.lcj.bff.driver.service.DriverService;
import com.lcj.bff.driver.service.OrderMessageService;
import com.lcj.common.util.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author : lcj
 * @create 2022/11/3 21:32
 */
@RestController
@RequestMapping("/driver")
@Tag(name = "DriverController", description = "司机模块Web接口")
public class DriverController {

    @Resource
    private DriverService driverService;

    @Resource
    private OrderMessageService orderMessageService;

    @Resource
    private DriverLocationService driverLocationService;

    @PostMapping("/registerNewDriver")
    @Operation(summary = "新司机注册")
    public Result registerNewDriver(@RequestBody @Valid RegisterNewDriverForm form) {
        Result registerResult = driverService.registerNewDriver(form);
        long userId = Convert.toLong(registerResult.get("userId"));
        registerResult.remove("userId");
        //在SaToken上面执行登陆，实际上就是缓存userId，然后才有资格拿到令牌
        StpUtil.login(userId);
        //生成Token令牌字符串（已加密）
        String token = StpUtil.getTokenInfo().getTokenValue();
        return registerResult.put("token", token);
    }

    @PostMapping("/updateDriverAuth")
    @Operation(summary = "更新实名认证信息")
    @SaCheckLogin
    public Result updateDriverAuth(@RequestBody @Valid UpdateDriverAuthForm form) {
        long driverId = StpUtil.getLoginIdAsLong();
        form.setDriverId(driverId);
        int rows = driverService.updateDriverAuth(form);
        return Result.ok().put("rows", rows);
    }

    @PostMapping("/createDriverFaceModel")
    @SaCheckLogin
    @Operation(summary = "创建司机人脸模型归档")
    public Result createDriverFaceModel(@RequestBody @Valid CreateDriverFaceModelForm form) {
        long driverId = StpUtil.getLoginIdAsLong();
        form.setDriverId(driverId);
        String result = driverService.createDriverFaceModel(form);
        return Result.ok().put("result", result);
    }


    @PostMapping("/verificateDriverFace")
    @SaCheckLogin
    @Operation(summary = "校验司机人脸是否正确")
    public Result vertificateDriverFace(@RequestBody @Valid CreateDriverFaceModelForm form) {
        long driverId = StpUtil.getLoginIdAsLong();
        form.setDriverId(driverId);
        String result = driverService.vertificateDriverFace(form);
        return Result.ok().put("result", result);
    }

    @PostMapping("/login")
    @Operation(summary = "登录系统")
    public Result login(@RequestBody @Valid LoginForm form) {
        Map map = driverService.login(form);
        if(map != null) {
            Long driverId = MapUtil.getLong(map, "id");
            Integer realAuth = MapUtil.getInt(map, "realAuth");
            boolean archive = MapUtil.getBool(map, "archive");
            StpUtil.login(driverId);
            String token = StpUtil.getTokenInfo().getTokenValue();
            return Result.ok().put("token", token).put("realAuth", realAuth).put("archive", archive);
        }
        return Result.ok();
    }

    @GetMapping("/logout")
    @Operation(summary = "退出登录系统")
    @SaCheckLogin
    public Result logout() {
        StpUtil.logout();
        return Result.ok();
    }

    @PostMapping("/searchDriverBaseInfo")
    @Operation(summary = "查询司机基本信息")
    @SaCheckLogin
    public Result searchDriverBaseInfo() {
        long driverId = StpUtil.getLoginIdAsLong();
        DriverIdForm form = new DriverIdForm(driverId);
        HashMap map = driverService.searchDriverBaseInfo(form);
        return Result.ok().put("result", map);
    }

    @PostMapping("/searchWorkbenchData")
    @Operation(summary = "查询司机工作台数据")
    @SaCheckLogin
    public Result searchWorkbenchData() {
        long driverId = StpUtil.getLoginIdAsLong();
        HashMap result = driverService.searchWorkbenchData(driverId);
        return Result.ok().put("result", result);
    }

    @GetMapping("/searchDriverAuth")
    @Operation(summary = "查询司机实名信息")
    @SaCheckLogin
    public Result searchDriverAuth(){
        long driverId = StpUtil.getLoginIdAsLong();
        HashMap res = driverService.searchDriverAuth(new DriverIdForm(driverId));
        return Result.ok().put("result", res);
    }

    @PostMapping(value = {"/startWork", "/stopWork"})
    @Operation(summary = "开始/停止接单")
    @SaCheckLogin
    public Result startWork(@RequestBody @Nullable UpdateLocationCacheForm locationForm) {
        long driverId = StpUtil.getLoginIdAsLong();
        DriverIdForm form = new DriverIdForm(driverId);
        //没传定位删除司机定位缓存
        if(locationForm == null) {
            driverLocationService.removeLocationCache(form);
        }
        //有传定位更新缓存
        else {
            locationForm.setDriverId(form.getDriverId());
            driverLocationService.updateLocationCache(locationForm);
        }

        //清空新订单消息列表
        orderMessageService.clearNewOrderQueue(form);
        return Result.ok();
    }

    @GetMapping("/searchCanStartWork")
    @Operation(summary = "查询司机能否开始工作")
    @SaCheckLogin
    public Result searchCanStartWork() {
        long driverId = StpUtil.getLoginIdAsLong();
        SearchCanStartWorkForm form_1 = new SearchCanStartWorkForm();
        form_1.setDriverId(driverId);
        form_1.setDate(new DateTime().toDateStr());
        HashMap map = driverService.searchCanStartWork(form_1);
        return Result.ok().put("result", map);
    }

    @PostMapping("/updateDriverSettings")
    @Operation(summary = "更新司机设置")
    @SaCheckLogin
    public Result updateDriverSettings(@RequestBody @Valid DriverSettingsForm form) {
        Long driverId = StpUtil.getLoginIdAsLong();
        form.setDriverId(driverId);
        Result res = driverService.updateDriverSettings(form);
        return res;
    }

    @PostMapping("/wallet/recharge")
    @Operation(summary = "司机钱包充值")
    @SaCheckLogin
    public Result recharge(@RequestBody @Valid DriverRechargeForm form) {
        Long driverId = StpUtil.getLoginIdAsLong();
        form.setDriverId(driverId);
        form.setTime(new DateTime());
        Result res = driverService.recharge(form);
        return res;
    }

    @PostMapping("/wallet/searchInfo")
    @Operation(summary = "司机钱包信息")
    @SaCheckLogin
    public Result searchInfo(@RequestBody @Valid DriverWalletInfoForm form) {
        Long driverId = StpUtil.getLoginIdAsLong();
        form.setDriverId(driverId);
        Map res = driverService.searchInfo(form);
        return Result.ok().put("data",res);
    }

    @PostMapping("/updatePhone")
    @Operation(summary = "更新司机电话")
    @SaCheckLogin
    public Result updatePhone(@RequestBody @Valid UpdatePhoneForm form) {
        Long driverId = StpUtil.getLoginIdAsLong();
        form.setDriverId(driverId);
        Result result = driverService.updatePhone(form);
        result.put("type", "updatePhone");
        return result;
    }

    @PostMapping("/sendSms")
    @Operation(summary = "发送验证码")
    public Result updatePhone(@RequestBody @Valid DriverSendSmsForm form) {
        Long driverId = StpUtil.getLoginIdAsLong();
        form.setDriverId(driverId);
        Result result = driverService.sendSmsCode(form);
        return result;
    }

    @PostMapping("/updateDriverHome")
    @Operation(summary = "更新司机家")
    @SaCheckLogin
    public Result updatePhone(@RequestBody @Valid UpdateDriverHomeForm form) {
        Long driverId = StpUtil.getLoginIdAsLong();
        form.setDriverId(driverId);
        Result result = driverService.updateDriverHome(form);
        return result;
    }
}

